package com.ypf.demo_ssm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ypf.demo_ssm.config.ServiceException;
import com.ypf.demo_ssm.entity.User;
import com.ypf.demo_ssm.service.impl.UserServiceImpl;
import com.ypf.demo_ssm.utils.JwtUtils;
import com.ypf.demo_ssm.dto.response.LoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
@Tag(name = "登录相关")
public class ApiController {

    private final JwtUtils jwtUtils;
    private final UserServiceImpl userServiceImpl;

    public ApiController(JwtUtils jwtUtils, UserServiceImpl userServiceImpl) {
        this.jwtUtils = jwtUtils;
        this.userServiceImpl = userServiceImpl;
    }

    @Operation(summary = "用户登录")
    @GetMapping("/login")
    public LoginVO login(@RequestParam(value = "account") String account,
                         @RequestParam(value = "password") String password) {
        // 校验账号和密码
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        queryWrapper.eq("password", password);
        User user = userServiceImpl.getOne(queryWrapper);
        if (user == null) {
            throw new ServiceException("账号或密码不正确");
        }
        // 调佣生成 token
        Map<String, Object> claims = new HashMap<>();
        claims.put("account", account);
        claims.put("password", password);
        String token = jwtUtils.generateToken(claims, "user");
        // 组装返回数据
        LoginVO loginVo = new LoginVO();
        loginVo.setToken(token);
        loginVo.setUserId(user.getId());
        loginVo.setUsername(user.getUsername());
        loginVo.setAccount(user.getAccount());
        return loginVo;
    }


}
